<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="盘点单号" prop="sessionNo">
        <el-input
          v-model="queryParams.sessionNo"
          placeholder="请输入盘点单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点人" prop="inventoryUser">
        <el-select
          v-model="queryParams.inventoryUser"
          placeholder="请选择盘点人"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="user in userOptions"
            :key="user.userId"
            :label="user.nickName"
            :value="user.nickName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备件仓库" prop="warehouseCode">
        <el-select
          v-model="queryParams.warehouseCode"
          placeholder="请选择备件仓库"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="w in warehouseOptions"
            :key="w.warehouseCode"
            :label="w.warehouseName"
            :value="w.warehouseCode"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-buttons" style="margin-bottom: 20px;">
      <!-- 左侧：搜索操作按钮 -->
      <div class="search-buttons">
        <el-button type="primary" size="small" @click="handleQuery" style="margin-right: 8px;">
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button size="small" @click="resetQuery" style="margin-right: 8px;">
          <i class="el-icon-refresh"></i> 重置
        </el-button>
        <el-button type="text" size="small" @click="toggleSearch">
          <i class="el-icon-arrow-down" v-if="!showSearch"></i>
          <i class="el-icon-arrow-up" v-else></i>
          {{ showSearch ? '收起' : '展开' }}
        </el-button>
      </div>

      <!-- 右侧：功能操作按钮 -->
      <div class="action-buttons">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:inventory:add']"
          style="margin-right: 8px;"
        >添加盘点单</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:inventory:export']"
        >导出</el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="inventoryList" style="width: 100%">
      <el-table-column label="盘点单号" align="center" prop="sessionNo" min-width="150" />
      <el-table-column label="计划盘点日期" align="center" prop="plannedDate" min-width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.plannedDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际盘点日期" align="center" prop="actualDate" min-width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.actualDate ? parseTime(scope.row.actualDate, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备件仓库" align="center" prop="warehouseCode" min-width="120">
        <template slot-scope="scope">
          <span>{{ getWarehouseName(scope.row.warehouseCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点人" align="center" prop="inventoryUser" min-width="100" />
      <el-table-column label="状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:inventory:query']"
          >明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            style="color:#F56C6C"
            v-hasPermi="['system:inventory:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.status === 'PENDING'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleExecute(scope.row)"
            v-hasPermi="['system:inventory:execute']"
          >执行盘点</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listInventory, delInventory } from "@/api/inventory/inventory"

export default {
  name: "Inventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 盘点表格数据
      inventoryList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sessionNo: null,
        inventoryUser: null,
        warehouseCode: null
      },
      // 仓库下拉选项
      warehouseOptions: [],
      // 用户下拉选项
      userOptions: []
    }
  },
  async created() {
    await Promise.all([this.loadWarehouses(), this.loadUsers()])
    await this.getList()
  },
  methods: {
    // 加载仓库列表
    loadWarehouses() {
      if (this.$apiWarehouseLoaded) return
      import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouseDTO || mod.listWarehouse || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
            this.warehouseOptions = res.data || res.rows || []
            this.$apiWarehouseLoaded = true
          })
        }
      }).catch(() => {})
    },
    // 加载用户列表
    loadUsers() {
      if (this.$apiUserLoaded) return
      import('@/api/system/user').then(mod => {
        const listFn = mod.listUser || mod.list
        if (listFn) {
          listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
            const users = res.rows || res.data || []
            // 根据昵称去重，使用Map确保唯一性
            const userMap = new Map()
            users.forEach(user => {
              if (user.nickName && !userMap.has(user.nickName)) {
                userMap.set(user.nickName, user)
              }
            })
            this.userOptions = Array.from(userMap.values())
            this.$apiUserLoaded = true
          })
        }
      }).catch(() => {})
    },
    /** 查询盘点列表 */
    getList() {
      this.loading = true
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 切换搜索显示 */
    toggleSearch() {
      this.showSearch = !this.showSearch
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/system/inventory-add' })
    },
    /** 明细按钮操作 */
    handleDetail(row) {
      this.$router.push({ path: `/system/inventory-detail/${row.sessionNo}` })
    },
    /** 执行盘点按钮操作 */
    handleExecute(row) {
      this.$router.push({ path: `/system/inventory-execute/${row.sessionNo}` })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除盘点单号为"' + row.sessionNo + '"的数据项？').then(function() {
        return delInventory(row.sessionNo)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    },
    /** 获取仓库名称 */
    getWarehouseName(code) {
      const warehouse = this.warehouseOptions.find(w => w.warehouseCode === code)
      return warehouse ? warehouse.warehouseName : code
    },
    /** 获取状态名称 */
    getStatusName(status) {
      const statusMap = {
        'PENDING': '待盘点',
        'COMPLETED': '盘点完成'
      }
      return statusMap[status] || status
    },
    /** 获取状态类型 */
    getStatusType(status) {
      const typeMap = {
        'PENDING': 'warning',
        'COMPLETED': 'success'
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  width: 100%;
}

.search-buttons {
  display: flex;
  align-items: center;
  flex: 1;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex: 1;
}

/* 统一按钮样式 */
.operation-buttons .el-button {
  border-radius: 4px;
  font-weight: 500;
}

.operation-buttons .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.operation-buttons .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.operation-buttons .el-button--text {
  color: #409EFF;
  padding: 8px 12px;
}

.operation-buttons .el-button--text:hover {
  color: #66b1ff;
}
</style>